package com.ruoyi.quartz.task;

import com.ruoyi.integration.response.DustResponse;
import com.ruoyi.integration.service.impl.DustMonitorDataServiceImpl;
import com.ruoyi.iot.dto.Dust;
import com.ruoyi.iot.mapper.DustMapper;
import com.ruoyi.iot.utils.IoTConverter;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Component("DustMonitorDataUpdateTask")
@RequiredArgsConstructor
public class DustMonitorDataUpdateTask {

    private final DustMapper dustIoTMapper;

    private final DustMonitorDataServiceImpl dustMonitorDataService;


    public void updateDustData() throws ExecutionException {

        // 获取当前数据库中所有离线设备ID
        List<String> currentOfflineDeviceIds = dustIoTMapper.getOfflineDeviceIds();

        // 获取传感器数据
        DustResponse dustResponse = dustMonitorDataService.fetchData();
        if (dustResponse == null || dustResponse.getData() == null) {
            return;
        }

        List<String> offlineDeviceIds = new ArrayList<>(); // 本次离线设备（状态=1）
        List<String> recoveryDeviceIds = new ArrayList<>(); // 本次恢复设备（原来设备离线，重新传递有效数据，则认为已恢复）
        List<DustResponse.DeviceData> validDeviceDataList = new ArrayList<>(); // 有效数据集

        for (DustResponse.DeviceData deviceData : dustResponse.getData()) {
            String deviceAddr = String.valueOf(deviceData.getDeviceAddr());

            long ts = deviceData.getTimeStamp();
            long now = System.currentTimeMillis();
            boolean invalidTime = ts < 1577808000000L || ts > now + 30 * 60 * 1000L;//datatime检查：是否早于2000年或是未来数据
            boolean isOffline = "offline".equals(deviceData.getDeviceStatus()) ;//设备状态检查

            // 数据无效 → 记录为离线
            if (isOffline || invalidTime) {
                offlineDeviceIds.add(deviceAddr);
                continue;
            }
            // 有效数据 → 判断是否是恢复
            if (currentOfflineDeviceIds.contains(deviceAddr)) {
                recoveryDeviceIds.add(deviceAddr);
            }
            validDeviceDataList.add(deviceData);
        }

        // 执行状态更新（仅更新需要变更的设备）
        if (!offlineDeviceIds.isEmpty()) {
            dustIoTMapper.updateStatus(offlineDeviceIds, 1); // 离线设备
        }
        if (!recoveryDeviceIds.isEmpty()) {
            dustIoTMapper.updateStatus(recoveryDeviceIds, 0); // 恢复设备
        }

        // 插入有效数据
        if (!validDeviceDataList.isEmpty()) {
            DustResponse validDustResponse = new DustResponse();
            validDustResponse.setData(validDeviceDataList);
            List<Dust> validDustList = IoTConverter.dustDataConvert(validDustResponse);


            dustIoTMapper.batchInsertDustData(validDustList);
        }
    }
}
